<template>
  <div class="task-list">
    <!-- 搜索和排序 -->
    <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6">
      <div class="w-full md:w-auto">
        <label for="search" class="sr-only">搜索任务</label>
        <div class="relative">
          <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
            <i class="fa fa-search text-gray-400"></i>
          </div>
          <input
            type="text"
            id="search"
            v-model="searchQuery"
            placeholder="搜索任务..."
            class="pl-10 pr-4 py-2 w-full md:w-64 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:text-white"
          >
        </div>
      </div>
      
      <div class="flex items-center gap-4">
        <label for="sort" class="text-sm font-medium text-gray-700 dark:text-gray-300">排序方式:</label>
        <select
          id="sort"
          v-model="sortBy"
          class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:text-white"
        >
          <option value="date">按创建时间</option>
          <option value="priority">按优先级</option>
          <option value="dueDate">按截止日期</option>
        </select>
        
        <button
          @click="clearAllTasks"
          class="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-md focus:outline-none focus:ring-2 focus:ring-red-500"
        >
          <i class="fa fa-trash mr-1"></i> 清除所有
        </button>
      </div>
    </div>
    
    <!-- 批量操作工具栏 -->
    <div v-if="selectedTaskIds.length > 0" class="bg-blue-50 dark:bg-blue-900/30 p-4 rounded-lg mb-6">
      <div class="flex flex-wrap gap-2">
        <button
          @click="batchMarkAsCompleted(true)"
          class="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-md transition-colors"
        >
          <i class="fas fa-check mr-2"></i>标记为完成
        </button>
        <button
          @click="batchMarkAsCompleted(false)"
          class="px-4 py-2 bg-yellow-600 hover:bg-yellow-700 text-white rounded-md transition-colors"
        >
          <i class="fas fa-times mr-2"></i>标记为未完成
        </button>
        <div class="relative">
          <select
            v-model="batchPriority"
            @change="batchUpdatePriority"
            class="pl-3 pr-10 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:text-white"
          >
            <option value="">更改优先级</option>
            <option value="high">高</option>
            <option value="medium">中</option>
            <option value="low">低</option>
          </select>
          <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700 dark:text-gray-300">
            <i class="fas fa-chevron-down text-xs"></i>
          </div>
        </div>
        <button
          @click="batchDelete"
          class="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-md transition-colors"
        >
          <i class="fas fa-trash mr-2"></i>删除所选
        </button>
      </div>
    </div>
    
    <!-- 调试信息 -->
    <div v-if="debugMode" class="bg-amber-100 dark:bg-amber-900/30 p-4 rounded-lg mb-6 text-sm">
      <div class="flex items-center justify-between mb-2">
        <h3 class="font-medium">调试信息</h3>
        <button @click="toggleDebugMode" class="text-sm text-blue-600 dark:text-blue-400">
          {{ debugMode ? '隐藏' : '显示' }}
        </button>
      </div>
      <p><strong>任务总数:</strong> {{ tasks.length }}</p>
      <p><strong>过滤后任务数:</strong> {{ filteredTasks.length }}</p>
      <p><strong>搜索查询:</strong> "{{ searchQuery }}"</p>
      <p><strong>排序方式:</strong> {{ sortBy }}</p>
      <pre class="text-xs mt-2 p-2 bg-white dark:bg-gray-800 rounded overflow-x-auto">
        {{ JSON.stringify(tasks[0] || {}, null, 2) }}
      </pre>
    </div>
    
    <!-- 空状态提示 -->
    <div v-if="tasks.length === 0" class="text-center py-12 bg-gray-50 dark:bg-gray-800 rounded-lg">
      <div class="mb-4 text-gray-400">
        <i class="fas fa-clipboard-list text-5xl"></i>
      </div>
      <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-2">暂无任务</h3>
      <p class="text-gray-500 dark:text-gray-400">添加你的第一个任务吧！</p>
    </div>
    
    <!-- 过滤后无结果提示 -->
    <div v-else-if="filteredTasks.length === 0" class="text-center py-12 bg-gray-50 dark:bg-gray-800 rounded-lg">
      <div class="mb-4 text-gray-400">
        <i class="fas fa-search text-5xl"></i>
      </div>
      <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-2">没有找到匹配的任务</h3>
      <p class="text-gray-500 dark:text-gray-400">尝试修改搜索条件或清除搜索</p>
      <button
        @click="clearSearch"
        class="mt-4 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md transition-colors"
      >
        <i class="fas fa-times mr-2"></i>清除搜索
      </button>
    </div>
    
    <!-- 任务卡片列表 -->
    <div class="space-y-4">
      <div 
        v-for="task in filteredTasks" 
        :key="task.id"
        class="bg-white dark:bg-gray-800 p-5 rounded-lg shadow-md border-l-4 transition-all duration-300 hover:shadow-lg"
        :class="{
          'border-l-green-500 bg-green-50 dark:bg-green-900/20': task.completed,
          'border-l-blue-500': !task.completed && task.priority === 'high',
          'border-l-yellow-500': !task.completed && task.priority === 'medium',
          'border-l-gray-500': !task.completed && task.priority === 'low'
        }"
      >
        <div class="flex items-start">
          <!-- 任务选择框 -->
          <div class="flex-shrink-0 mr-4">
            <input
              type="checkbox"
              v-model="selectedTaskIds"
              :value="task.id"
              class="h-5 w-5 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
            >
          </div>
          
          <!-- 任务内容 -->
          <div class="flex-1 min-w-0">
            <div class="flex items-start justify-between">
              <!-- 任务标题 -->
              <h3 class="text-lg font-medium text-gray-900 dark:text-white truncate">
                <span 
                  :class="{
                    'line-through text-gray-500 dark:text-gray-400': task.completed,
                    'font-bold': !task.completed
                  }"
                >
                  {{ task.title }}
                </span>
              </h3>
              
              <!-- 任务操作按钮 -->
              <div class="ml-4 flex-shrink-0 flex">
                <!-- 任务完成状态切换 -->
                <button
                  @click="toggleTaskCompleted(task)"
                  class="p-1.5 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
                  :class="{
                    'text-green-500': task.completed,
                    'text-gray-400': !task.completed
                  }"
                  aria-label="切换任务状态"
                >
                  <i class="fas fa-check-circle"></i>
                </button>
                
                <!-- 删除按钮 -->
                <button
                  @click="deleteTask(task.id)"
                  class="ml-2 p-1.5 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-red-500 transition-colors"
                  aria-label="删除任务"
                >
                  <i class="fa fa-trash"></i>
                </button>
              </div>
            </div>
            
            <!-- 任务信息 -->
            <div class="mt-2 flex flex-wrap items-center gap-2 text-sm">
              <!-- 优先级标签 -->
              <span 
                class="px-2 py-0.5 rounded-full text-xs font-medium"
                :class="{
                  'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300': task.priority === 'high',
                  'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300': task.priority === 'medium',
                  'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300': task.priority === 'low'
                }"
              >
                {{ task.priority === 'high' ? '高' : task.priority === 'medium' ? '中' : '低' }}
              </span>
              
              <!-- 截止日期 -->
              <span class="text-gray-500 dark:text-gray-400">
                <i class="fas fa-calendar-alt mr-1"></i>
                {{ formatDate(task.dueDate) || '无截止日期' }}
              </span>
              
              <!-- 标签 -->
              <div class="flex flex-wrap gap-1">
                <span 
                  v-for="tag in task.tags" 
                  :key="tag"
                  class="px-2 py-0.5 rounded-full text-xs bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300"
                >
                  {{ tag }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits } from 'vue';

const props = defineProps({
  tasks: {
    type: Array,
    required: true
  }
});

const emits = defineEmits([
  'task-updated',
  'task-deleted',
  'tasks-cleared'
]);

const searchQuery = ref('');
const sortBy = ref('date');
const selectedTaskIds = ref([]);
const batchPriority = ref('');
const debugMode = ref(true);

// 过滤后的任务列表
const filteredTasks = computed(() => {
  let result = [...props.tasks];
  
  // 按搜索词过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(task => 
      task.title.toLowerCase().includes(query) || 
      task.tags.some(tag => tag.toLowerCase().includes(query))
    );
  }
  
  // 按排序方式排序
  result.sort((a, b) => {
    if (sortBy.value === 'date') {
      return new Date(b.createdAt) - new Date(a.createdAt);
    } else if (sortBy.value === 'priority') {
      const priorityOrder = { 'high': 3, 'medium': 2, 'low': 1 };
      return priorityOrder[b.priority] - priorityOrder[a.priority];
    } else if (sortBy.value === 'dueDate') {
      const aDate = a.dueDate ? new Date(a.dueDate) : new Date(9999, 11, 31);
      const bDate = b.dueDate ? new Date(b.dueDate) : new Date(9999, 11, 31);
      return aDate - bDate;
    }
    return 0;
  });
  
  return result;
});

const toggleDebugMode = () => {
  debugMode.value = !debugMode.value;
};

const toggleTaskCompleted = (task) => {
  const updatedTask = {
    ...task,
    completed: !task.completed
  };
  
  emits('task-updated', updatedTask);
};

const deleteTask = (taskId) => {
  if (confirm('确定要删除这个任务吗？')) {
    emits('task-deleted', taskId);
  }
};

const clearSearch = () => {
  searchQuery.value = '';
};

const batchMarkAsCompleted = (completed) => {
  if (selectedTaskIds.value.length === 0) return;
  
  selectedTaskIds.value.forEach(taskId => {
    const task = props.tasks.find(t => t.id === taskId);
    if (task) {
      emits('task-updated', {
        ...task,
        completed
      });
    }
  });
  
  selectedTaskIds.value = [];
};

const batchUpdatePriority = () => {
  if (selectedTaskIds.value.length === 0 || !batchPriority.value) return;
  
  selectedTaskIds.value.forEach(taskId => {
    const task = props.tasks.find(t => t.id === taskId);
    if (task) {
      emits('task-updated', {
        ...task,
        priority: batchPriority.value
      });
    }
  });
  
  selectedTaskIds.value = [];
  batchPriority.value = '';
};

const batchDelete = () => {
  if (selectedTaskIds.value.length === 0) return;
  
  if (confirm(`确定要删除选中的 ${selectedTaskIds.value.length} 个任务吗？`)) {
    selectedTaskIds.value.forEach(taskId => {
      emits('task-deleted', taskId);
    });
    
    selectedTaskIds.value = [];
  }
};

const clearAllTasks = () => {
  if (confirm('确定要清除所有任务吗？')) {
    emits('tasks-cleared');
  }
};

const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
};
</script>

<style scoped>
.task-list {
  transition: all 0.3s ease;
}

.task-card {
  transition: all 0.2s ease;
}

.task-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.priority-tag {
  transition: all 0.2s ease;
}

.priority-tag:hover {
  transform: scale(1.05);
}

.tag {
  transition: all 0.2s ease;
}

.tag:hover {
  transform: translateY(-1px);
}
</style>
    